package com.spider.admin.logs.service;


import com.spider.admin.exception.SpiderException;
import com.spider.admin.service.async.AsyncService;
import com.spider.admin.store.primary.mapper.LogSettingsMapper;
import com.spider.admin.utils.CommonUtil;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class LogSettingService {

    @Autowired
    private LogSettingsMapper logSettingsMapper;

    @Resource
    private AsyncService asyncService;

    public Map<String, String> getLogSettingsByServiceId(String serviceId) throws SpiderException {
        List<Map<String, String>> result = logSettingsMapper.queryLogSettingsByServiceId(serviceId);
        Map<String, String> settings = new HashMap<>();
        if (result != null && !result.isEmpty()) {
            for (Map<String, String> map : result) {
                settings.put(map.get("setting_key"),map.get("setting_value"));
            }
        }
        return settings;
    }

    @Transactional
    public boolean updateLogSettings(String serviceId, Map<String, String> settingsMap) throws SpiderException {
        boolean bol = false;
        if (settingsMap != null && !settingsMap.isEmpty()) {
            logSettingsMapper.deleteLogSettingsByServiceId(serviceId);
            for (String key : settingsMap.keySet()) {
                logSettingsMapper.insertLogSetting(CommonUtil.getUniqueKey(), serviceId, key, settingsMap.get(key));
            }

            asyncService.asyncRefashLogsSettingsCache();
            bol = true;
        }
        return bol;
    }
}
